package com.qyer.commons.mc.reloader;

import com.qyer.commons.mc.converter.Converter;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;

/**
 * User: Z J Wu Date: 2015/08/12 Time: 22:15 Package: com.qyer.dsp.cache
 */
public class FileReloader<T> extends Reloader<T> {

  private static final Logger LOGGER = LoggerFactory.getLogger(FileReloader.class);

  private Converter<String, T> converter;

  public FileReloader(String filePath, Converter<String, T> converter) {
    super(filePath);
    this.converter = converter;
  }

  @Override public T _reload() throws Exception {
    File f = new File(getReloadResource());
    String line;
    try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(f)))) {
      while ((line = br.readLine()) != null) {
        line = StringUtils.trimToNull(line);
        if (StringUtils.isBlank(line)) {
          continue;
        }
        if (line.startsWith("//") || line.startsWith("#")) {
          continue;
        }
        break;
      }
    }
    return converter.convert(line);
  }
}
